package com.example.demo.service.impl;

import com.example.demo.mapper.UserMapper;
import com.example.demo.po.User;
import com.example.demo.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);

    @Resource
    private UserMapper userMapper;

    @Override
    public User getById(Long id) {
        return userMapper.selectById(id);
    }

    @Override
    public List<User> getAll() {
        return userMapper.selectAll();
    }

    @Override
    public boolean create(User user) {
        boolean result = userMapper.insert(user) > 0;
        log.info("Create user: {} result: {}", user, result);
        return result;
    }

    @Override
    public boolean update(User user) {
        boolean result = userMapper.update(user) > 0;
        log.info("Update user: {} result: {}", user, result);
        return result;
    }

    @Override
    public boolean deleteById(Long id) {
        boolean result = userMapper.deleteById(id) > 0;
        log.info("Delete user by id: {} result: {}", id, result);
        return result;
    }

    @Override
    public List<User> getByAgeRange(int minAge, int maxAge) {
        // return userMapper.selectByAgeRange(minAge, maxAge); // 注释掉，UserMapper 无此方法
        return null;
    }

    @Override
    @Transactional
    public boolean batchCreate(java.util.List<User> users) {
        // 假设底层支持批量插入
        int count = 0;
        for (User user : users) {
            count += userMapper.insert(user);
        }
        log.info("Batch create users: {} result: {}", users, count == users.size());
        return count == users.size();
    }

    @Override
    public java.util.List<User> listPage(int pageNum, int pageSize) {
        int offset = (pageNum - 1) * pageSize;
        return userMapper.selectPage(offset, pageSize);
    }

    @Override
    public User getByPhone(String phone) {
        return userMapper.getByPhone(phone);
    }
}